package com.fujimana.rockincat.restree.init.filter;

import com.fujimana.rockincat.restree.annotation.filter.Filter;
import com.fujimana.rockincat.restree.annotation.filter.Sort;
import com.fujimana.rockincat.restree.init.Handler;
import com.fujimana.rockincat.restree.init.Item;
import com.fujimana.rockincat.restree.util.ClassUtils;

public class FilterHandler implements Handler<Item> {

	@Override
	public Item handle(String resource) {
		Class<?> clazz = ClassUtils.loadClass(resource);
		Filter f = clazz.getAnnotation(Filter.class);
		
		String before = null;
		String after = null;
		
		Sort s = clazz.getAnnotation(Sort.class);
		
		if(s != null) {
			before = s.before().getName();
			after = s.after().getName();
		}
		
		return new FilterItem(f.urlPattern(),clazz, before, after);
	}

	@Override
	public boolean isHandle(String resource) {
		if (!resource.endsWith(".class")) {
			return false;
		}
		
		Class<?> clazz = ClassUtils.loadClass(resource);
		
		if(clazz == null) {
			return false;
		}	

		return clazz.getAnnotation(Filter.class) != null;
	}

}
